package com.zjut.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zjut.domain.User;
import com.zjut.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping
    public Result save(@RequestBody User user) {
        if (user.getUsername() == null) {
            return new Result(Code.SAVE_ERR, null, "用户名不能为空");
        } else if (userService.getByUsername(user.getUsername()) != null) {
            return new Result(Code.SAVE_ERR, null, "该用户名已存在");
        }
        if (user.getPassword() != "" && user.getPassword() != null) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        boolean flag = userService.save(user);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        if (user.getTelephone() != null) {
            if (user.getTelephone().getBytes().length > 20) {
                return new Result(Code.UPDATE_ERR, null, "修改失败,请检查表单");
            }
        }
        if (user.getName() != null) {
            if (user.getName().getBytes().length > 10) {
                return new Result(Code.UPDATE_ERR, null, "修改失败,请检查表单");
            }
        }
        boolean flag = userService.update(user);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @PutMapping("/password")
    public Result updatePassword(@RequestBody User user) {
        System.out.println(user);
        boolean flag = userService.update(user);
        return new Result(flag ? Code.MODIFY_PASSWORD_OK : Code.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = userService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        User user = userService.getById(id);
        Integer code = user != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user != null ? "" : "用户查询失败，请重试！";
        return new Result(code, user, msg);
    }

    @GetMapping
    public Result getAll() {
        List<User> userList = userService.getAll();
        Integer code = userList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = userList != null ? "" : "用户查询失败，请重试！";
        return new Result(code, userList, msg);
    }

    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody User user) {
        if (user.getPassword() == null || user.getUsername() == null) {
            return new Result(Code.LOGIN_NULL_ERR, null, "用户名或密码不能为空");
        }
        if (userService.getByUsername(user.getUsername()) == null) {
            return new Result(Code.USERNAME_ERR, null, "用户名不存在，请注册");
        }
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (userService.getByUsername(user.getUsername()) == null) {
            return new Result(Code.USERNAME_ERR, null, "用户名不存在，请注册");
        }
        User user1 = userService.getByUsernameAndPassword(user.getUsername(), password);
        if (user1 == null) {
            return new Result(Code.PASSWORD_ERR, null, "密码错误，请重新输入");
        }
        if (user1.getStatus() == 0) {
            return new Result(Code.STATUS_ERR, null, "账号已被禁用");
        } else if (user1.getStatus() == 1) {
            request.getSession().setAttribute("user", user1.getId());
            return new Result(Code.USER_LOGIN_OK, user1, "用户登录成功");
        }
        request.getSession().setAttribute("user", user1.getId());
        return new Result(Code.ADMIN_LOGIN_OK, user1, "管理员登录成功");
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (user.getPassword() == null || user.getUsername() == null) {
            return new Result(Code.REGISTER_ERR, null, "用户名或密码不能为空");
        }
        if (user.getUsername().getBytes().length > 10) {
            return new Result(Code.USERNAME_ERR, null, "用户名长度不能超过10个字节");
        }
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        if (userService.getByUsername(user.getUsername()) != null) {
            return new Result(Code.REGISTER_ERR, null, "该用户名已存在");
        }
        userService.save(user);
        return new Result(Code.REGISTER_OK, user, "注册成功,请登录");
    }

    //登出功能
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return new Result(Code.LOGIN_OUT_OK, null, "已成功退出,欢迎下次登录");
    }

    //修改密码校验功能
    @PostMapping("/check")
    public Boolean check(@RequestBody User user) {
        if (userService.getByUsernameAndPassword(user.getUsername(), user.getPassword()) == null) {
            return false;
        }
        return true;
    }

    @GetMapping("{currentPage}/{pageSize}")
    public Result getPage(@PathVariable int currentPage, @PathVariable int pageSize, User user) {
        IPage<User> userList = userService.getPage(currentPage, pageSize, user);
        if (currentPage > userList.getPages()) {
            userList = userService.getPage((int) userList.getPages(), pageSize, user);
        }
        Integer code = userList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = userList != null ? "" : "数据查询失败，请重试！";
        return new Result(code, userList, msg);
    }
}
